package it.blueocean.acanto.taglibrary.jsp.taglib.tags.dataset;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;

public class QueryParamTag extends BodyTagSupport
{
	private static final long serialVersionUID = 1L;

	private Object value_;

	private Object defaultValue_;

	private String valueExpr_;

	private String defaultValueExpr_;

	public void setDefaultValue(String paramString)
	{
		this.defaultValueExpr_ = paramString;
	}

	public void setValue(String paramString)
	{
		this.valueExpr_ = paramString;
	}

	private void evaluateExpressions() throws JspException
	{
		if(this.valueExpr_ != null)
			this.value_ = ExpressionEvaluatorManager.evaluate("value", this.valueExpr_, Object.class, this,
					this.pageContext);
		else
			this.value_ = null;
		if(this.defaultValueExpr_ != null)
			this.defaultValue_ = ExpressionEvaluatorManager.evaluate("defaultValue", this.defaultValueExpr_,
					Object.class, this, this.pageContext);
		else
			this.defaultValue_ = null;
	}

	public int doStartTag() throws JspException
	{
		evaluateExpressions();
		if(this.value_ == null)
			return 2;
		return 6;
	}

	public int doAfterBody() throws JspException
	{
		BodyContent localBodyContent = getBodyContent();
		if((localBodyContent != null) && (localBodyContent.getString() != null)
				&& (!(localBodyContent.getString().equals(""))))
			this.value_ = localBodyContent.getString();
		return 6;
	}

	public int doEndTag() throws JspException
	{
		DataSetTag localDataSetTag = (DataSetTag) findAncestorWithClass(this, DataSetTag.class);
		
		if(localDataSetTag == null)
		{
			throw new JspException("QueryParam tag must be nested in a DataSetTag");
		}
		
		Object localObject;
		
		if(this.value_ != null)
		{
			localObject = this.value_;
		}
		else if(this.defaultValue_ != null)
		{
			localObject = this.defaultValue_;
		}
		else
		{
			localObject = "";
		}
		
		localDataSetTag.setParam(null, localObject);
		
		return 6;
	}
}
